import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class Jedis12 {
    private static JedisPool jedisPool;

    static {
        //创建并设置连接池配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(50);
        config.setMaxIdle(10);
        config.setMinIdle(7);
        config.setMaxWaitMillis(1000);
        config.setTestOnBorrow(true);

        //创建Jedis连接池
        jedisPool = new JedisPool(
                config,
                "127.0.0.1",
                6379,
                10000,
                null,
                0
        );
    }   //static块结束

    public void destroy(){
        if (!(jedisPool == null || jedisPool.isClosed())){
            jedisPool.close();  //关闭连接池
        }
    }

    public boolean set(String key, String value){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();  //从池中获取Jedis实例
            jedis.set(key, value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            //返回到连接池
            if (jedis != null){
                jedis.close();
            }
        }
    }

    /**
     * 获取数据
     *
     */
    public String get(String key){
        String value = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource(); //从池中获取Jedis实例
            value = jedis.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //返还到连接池
            if (jedis != null){
                jedis.close();
            }
            return value;
        }
    }

    /**
     * 设置
     *
     */
    public Long expire(String key,int seconds){
        Long count = new Long(0);
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            count = jedis.expire(key,seconds);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis!=null){
                jedis.close();
            }
        }
        return count;
    }

    public Long ttl(String key){
        Long count = new Long(0);
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            count = jedis.ttl(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis!=null){
                jedis.close();
            }
        }
        return count;
    }

    public Boolean exists(String key){
        Boolean be = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            be = jedis.exists(key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return be;
    }
}
